package com.fc.v2.controller.api;


import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceResponse;
import com.fc.v2.common.conf.redis.RedisService;
import com.fc.v2.common.domain.AjaxResult;
import com.fc.v2.model.MapObject;
import com.fc.v2.model.dto.AiResultDto;
import com.fc.v2.model.param.WriteParam;
import com.fc.v2.util.AliSmsUtils;
import com.fc.v2.util.IotUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Api(tags = "主控制器")
@RestController
@RequestMapping("/api/main")
public class AMainController {
    @Value("${ai.server}")
    private String pythonUrl;
    @Autowired
    private RedisService redisService;

    String pcDeviceName = "kVuFHnqxb0ZbtnW0Z4IK";
    String piDeviceName = "tPkkOeaKNQioD2SwzEGz";


    @ApiOperation(value = "获取ai诗词")
    @GetMapping("/ai")
    public AjaxResult get(String keys, Integer type) {
        if( StrUtil.isEmpty(keys)){
            throw new RuntimeException("关键词不得为空");
        }
        String keyCode = keys.hashCode() + "";
        String[] split = keys.split(" ");
        if(split.length > 4){
            throw new RuntimeException("关键词不得多于4个");
        }
        for (String s : split) {
            if(s.length()>4){
                throw new RuntimeException("关键词长度不得超出4个字符");
            }
            if(!Validator.isChinese(s)){
                throw new RuntimeException("关键词必须为汉字");
            }
        }
        if (type == 2) {
            //查看缓存
            if(redisService.exists(keyCode)){
                return AjaxResult.successData(200, new MapObject().put("type", 1)
                        .put("content", redisService.getCacheObject(keyCode)));
            }

            //请求诗词
            String result = HttpUtil.post("http://" + pythonUrl + "/ai/gen", JSONUtil.toJsonStr(new MapObject().put("keys", keys)));
            AiResultDto aiResultDto = JSONUtil.toBean(result, AiResultDto.class);
            if (aiResultDto.getCode() != 200) {
                return AjaxResult.error("响应错误");
            }
            //设置缓存
            redisService.setCacheObject(keyCode,aiResultDto.getAns(),10L, TimeUnit.MINUTES);
            return AjaxResult.successData(200, new MapObject().put("type", 1)
                    .put("content", aiResultDto.getAns()));
        } else {
            return AjaxResult.successData(200, new MapObject().put("type", 1)
                    .put("content", "{" +
                            "         \"title\":\"静夜思\"," +
                            "         \"author\":\"李白\"," +
                            "         \"dynasty\":\"唐\"," +
                            "         \"body\":\"床前看月光，|疑是地上霜。|抬头望山月，|低头思故乡。|\"" +
                            "      }")
            );
        }

    }



    @ApiOperation(value = "接受诗词并发布")
    @PostMapping("/recPoemAndPub")
    public AjaxResult recPoemAndPub(@RequestBody WriteParam writeParam){
        InvokeThingServiceResponse response = IotUtils.publish(pcDeviceName, writeParam.toMap(), "myWriteTask");
        if(response!=null && response.getSuccess()){
            return AjaxResult.success();
        }else{
            return AjaxResult.error(response==null?"pub消息失败":response.getErrorMessage());
        }
    }

    @ApiOperation(value = "接受gcode并发布")
    @PostMapping("/recGcodeAndPub")
    public AjaxResult recGcodeAndPub(@RequestBody WriteParam writeParam){
        InvokeThingServiceResponse response = IotUtils.publish(piDeviceName, writeParam.toMap(), "myWriteTask");
        if(response!=null && response.getSuccess()){
            return AjaxResult.success();
        }else{
            return AjaxResult.error(response==null?"pub消息失败":response.getErrorMessage());
        }
    }

}
